/*
 * Created on 2005-9-21
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dcivision.form.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableWorkbook;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.form.bean.FormData;
import com.dcivision.form.bean.FormDataElement;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSubmission;
import com.dcivision.form.dao.FormDataDAObject;
import com.dcivision.form.dao.FormDataElementDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSubmissionDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;

/**
 * @author vera
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ListFormAuditTrailAction extends AbstractListAction {

  public ListFormAuditTrailAction() {
    super();
    this.setListName("formAuditTrailList");
    this.setListFunctionName("getFormAuditTrailList");
  }
 
  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormSubmissionDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_MONITOR);
  }

  
  public void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    ListFormSubmissionForm listForm=(ListFormSubmissionForm)form;
    FormSubmissionDAObject formSubmissionDAO=new FormSubmissionDAObject(sessionContainer,conn);
    FormDataElementDAObject formDataElementDAO = new FormDataElementDAObject(sessionContainer,conn);
    FormDataDAObject formDataDAO = new FormDataDAObject(sessionContainer,conn);

    List result=new ArrayList();
    result=formSubmissionDAO.getFormAuditTrailList(form);
    String[] basicSearchField = listForm.getDisplayElementField();
    boolean hasSelectElement = false; 
    if (!Utility.isEmpty(basicSearchField) && !"null".equals(basicSearchField)){
      for (int k=0; k<basicSearchField.length; k++){
    	if (!Utility.isEmpty(basicSearchField[k].toString()) && !"null".equals(basicSearchField[k])){
    	  hasSelectElement = true;
    	  break;
    	}
      }
    }
       
    for(int i=0;i<result.size();i++){
      FormSubmission formSubmission = (FormSubmission)result.get(i);
      //get list:
      int dataSeq = 0,preDataSeq = 0;      
      List formDataElementList = new ArrayList();
      List formDataList = new ArrayList();
      List preFormDataList = new ArrayList();
      List totalFormDataList = new ArrayList();
      if (!Utility.isEmpty(formSubmission.getSeq()) && !"null".equals(formSubmission.getSeq())){
        dataSeq = formSubmission.getSeq().intValue();
      }
      if (dataSeq>0){
        formDataElementList = formDataElementDAO.getFormDataElementListBySeq(new Integer(dataSeq));
        for (int j=0; j<formDataElementList.size(); j++){
          FormDataElement formDataElement = (FormDataElement)formDataElementList.get(j);
          preDataSeq = formDataElementDAO.getPreviousElementSeqBySubmissionIDElementIDSeq(
               formDataElement.getSubmissionID(),
               formDataElement.getElementID(),
               formDataElement.getSeq());
          
          boolean isViewElement = false;
          if (hasSelectElement){
            for (int k=0; k<basicSearchField.length; k++){
              if (!Utility.isEmpty(basicSearchField[k].toString()) && formDataElement.getElementID().intValue() == Integer.parseInt(basicSearchField[k].toString())){
              	isViewElement = true;
              	break;
              }
            }
          }else{
          	isViewElement = true;
          }
          if (!isViewElement){continue;}
          formDataList = formDataDAO.getDataValueListBySubmissionIDElementIDSeq(
              formDataElement.getSubmissionID(),
              formDataElement.getElementID(),
              new Integer(dataSeq));  
          if (preDataSeq>0){
            preFormDataList = formDataDAO.getDataValueListBySubmissionIDElementIDSeq(
                formDataElement.getSubmissionID(),
                formDataElement.getElementID(),
                new Integer(preDataSeq));   
            if (preFormDataList.size()==formDataList.size()){
              for(int n=0; n<preFormDataList.size(); n++){
                FormData preFormData = (FormData)preFormDataList.get(n);
                FormData formData = (FormData)formDataList.get(n);
                
                if (!formData.equalsData(preFormData)){    
                	formData.setPreDataString(preFormData.getDataString());
                  totalFormDataList.add(formDataList);
                }
              }
            }else{
              if (!Utility.isEmpty(formDataList)){
                totalFormDataList.add(formDataList); 
              }
            }
          }else{
          	if (!Utility.isEmpty(formDataList)){
              totalFormDataList.add(formDataList);
          	}
          }
          
        }
        formSubmission.setFormDataList(totalFormDataList);
      }
      
    }
    request.setAttribute(this.getListName(),result);
    
  }
  
  
  public ActionForward execute(ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
  throws ServletException {
    HttpSession session = request.getSession();
    AbstractSearchForm searchForm = (AbstractSearchForm)form;
    String opMode = searchForm.getOpMode();
    String navMode = searchForm.getNavMode();
    String formRecordID = request.getParameter("formRecordID");
    
    //Set Page Title
    ListFormSubmissionForm listForm = (ListFormSubmissionForm)form;
    FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
    FormRecord formRecord = (FormRecord)formRecordDAO.getByFormRecordID(listForm.getFormRecordID());
    request.setAttribute("formRecord", formRecord);
    
    if(!Utility.isEmpty(listForm.getSearchSubmitter())){
      ((ListFormSubmissionForm)searchForm).setSearchSubmitter(listForm.getSearchSubmitter());
    }
    if (FormRecord.EXPORT_EXCEL_FILE.equals(request.getParameter("operationType"))){
      this.getListData(mapping,(AbstractSearchForm)form,request,response);
      expToExcel(request,response,form);
      return null;       
    }
    return super.execute(mapping,form,request,response);
  }
  
  public void expToExcel(HttpServletRequest request,HttpServletResponse response, ActionForm form){
    try{
     
      response.setContentType("APPLICATION/OCTET-STREAM");
      response.addHeader("Content-Transfer-Encoding", "base64");
      String filename = "FormAuditTrail.xls";
      response.addHeader("Content-Disposition", "attachment; filename=" + filename + "\"");
      WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 13, WritableFont.BOLD);
      WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
      WritableFont bodyFont = new WritableFont(WritableFont.ARIAL, 10);
      WritableFont footerFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
      WritableCellFormat titleCellFormat = new WritableCellFormat(titleFont);
      titleCellFormat.setAlignment(Alignment.RIGHT);
      WritableCellFormat headerCellFormat = new WritableCellFormat(headerFont);
      WritableCellFormat bodyCellFormat = new WritableCellFormat(bodyFont);
      WritableCellFormat numberCellFormat = new WritableCellFormat(bodyFont,NumberFormats.FLOAT);
      WritableCellFormat integerCellFormat = new WritableCellFormat(bodyFont,NumberFormats.INTEGER);
      WritableCellFormat footerCellFormat = new WritableCellFormat(footerFont);
      bodyCellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); 
      headerCellFormat.setBackground(Colour.GOLD);
      
      WritableCellFormat bodyCellFormatGray = new WritableCellFormat(bodyFont);
      bodyCellFormatGray.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); 
      bodyCellFormatGray.setBackground(Colour.GRAY_25);      
      WritableCellFormat setBodyCellFormat = bodyCellFormat;
      
      jxl.write.Label    slabel;
      ServletOutputStream sos =response.getOutputStream();
      WritableWorkbook xslwork=Workbook.createWorkbook(sos);
      
      int rowSpaceNuber=3;
      int iCol = -1,iRow = 4, sectionNum = 0;
      int pageListSize =0;
      int tmpRow =0;
      Integer pageID = new Integer(0);
       
      List resultList = (List)request.getAttribute(this.getListName());
      FormRecord formRecord = (FormRecord)request.getAttribute("formRecord");
      
      jxl.write.WritableSheet ws=xslwork.createSheet("FormAuditTrail",1);
      slabel=new jxl.write.Label(4,1,formRecord.getTitle()+" [ "+formRecord.getFormCode() +"]",titleCellFormat);
      ws.addCell(slabel);
      
      slabel=new jxl.write.Label(0,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"workflow.columnheader.workflow_code"),headerCellFormat);
      ws.addCell(slabel);
      slabel=new jxl.write.Label(1,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"workflow.columnheader.track_id"),headerCellFormat);
      ws.addCell(slabel);
      slabel=new jxl.write.Label(2,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"common.label.updater"),headerCellFormat);
      ws.addCell(slabel);
      slabel=new jxl.write.Label(3,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"common.label.update_date"),headerCellFormat);
      ws.addCell(slabel);
      slabel=new jxl.write.Label(4,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"form.label.element"),headerCellFormat);
      ws.addCell(slabel);
      slabel=new jxl.write.Label(5,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"form.columnheader.original"),headerCellFormat);
      ws.addCell(slabel);
      slabel=new jxl.write.Label(6,3,MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(),"form.columnheader.new_value"),headerCellFormat);
      ws.addCell(slabel);
      
   
      for (int p=0 ;p<resultList.size(); p++){
        FormSubmission formSubmission = (FormSubmission)resultList.get(p);    
        setBodyCellFormat = p%2!=0 ? bodyCellFormatGray : bodyCellFormat;              
        slabel=new jxl.write.Label(0,iRow,!Utility.isEmpty(formSubmission.getWorkflowCode()) && !"null".equals(formSubmission.getWorkflowCode()) ? formSubmission.getWorkflowCode() : "N/A" ,setBodyCellFormat);
        ws.addCell(slabel);
        slabel=new jxl.write.Label(1,iRow,!Utility.isEmpty(formSubmission.getWorkflowCode()) && !"null".equals(formSubmission.getWorkflowCode()) ? formSubmission.getTrackID().toString() : "N/A" ,setBodyCellFormat);
        ws.addCell(slabel);
        slabel=new jxl.write.Label(2,iRow,!Utility.isEmpty(formSubmission.getCreatorName()) && !"null".equals(formSubmission.getCreatorName()) ? formSubmission.getCreatorName().toString() : "N/A" ,setBodyCellFormat);
        ws.addCell(slabel);
        slabel=new jxl.write.Label(3,iRow,!Utility.isEmpty(formSubmission.getCreateDate()) && !"null".equals(formSubmission.getCreateDate()) ? formSubmission.getCreateDate().toString().substring(0,10) : "N/A" ,setBodyCellFormat);
        ws.addCell(slabel);

        tmpRow = iRow;
        for (int n=0;n<formSubmission.getFormDataList().size();n++){            
          List tmpformDataList = (List)(formSubmission).getFormDataList().get(n);        
          for (int nn=0; nn<tmpformDataList.size(); nn++){
            FormData tmpFormData = (FormData)tmpformDataList.get(nn);
            slabel=new jxl.write.Label(4,iRow,tmpFormData.getElementName(),setBodyCellFormat);
            ws.addCell(slabel);
            slabel=new jxl.write.Label(5,iRow,tmpFormData.getPreDataString(),setBodyCellFormat);
            ws.addCell(slabel);
            slabel=new jxl.write.Label(6,iRow,tmpFormData.getDataString(),setBodyCellFormat);
            ws.addCell(slabel);
            iRow++;
          }
        }
        if (iRow>tmpRow){
          ws.mergeCells(0,tmpRow,0,iRow-1);  
          ws.mergeCells(1,tmpRow,1,iRow-1);  
          ws.mergeCells(2,tmpRow,2,iRow-1);
          ws.mergeCells(3,tmpRow,3,iRow-1);  
        }else{
          iRow++;
        }
        

      }
      
      xslwork.write();
      xslwork.close();
      sos.close();
    } catch(Exception e){
       log.error(e, e);
    }
  }

}
